﻿using System.Collections.Generic;

namespace WindowsPhoneMvp.Navigation.Parsing
{
    public sealed class NavigationParser : INavigationParser
    {
        public NavigationData Parse(string url)
        {
            // Based on format of /Views/ViewFolder/ViewName.xaml?ParamName=Value
            if (url.Contains("/"))
            {
                url = url.Substring(url.LastIndexOf("/")).Trim('/');
                var tokens = url.Split('?');
                if (tokens.Length == 0) return new NavigationData("homepage");

                var view = tokens[0].Replace(".xaml", "");
                var navigationData = new NavigationData(view);

                if (tokens.Length == 1)
                {
                    return navigationData;
                }

                if (tokens[1].Contains("&"))
                {
                    //multiple
                    foreach(var parameter in tokens[1].Split('&'))
                    {
                        navigationData.With(ParseKeyValue(parameter));
                    }
                }
                else
                {
                    navigationData.With(ParseKeyValue(tokens[1]));
                }
                return navigationData;
            }

            return new NavigationData("homepage");
        }

        private KeyValuePair<string,string> ParseKeyValue(string data)
        {
            var split = data.Split('=');
            return new KeyValuePair<string, string>(split[0], split[1]);
        }

        public string FromData(NavigationData navigationData)
        {
            if (navigationData == null) return string.Empty;
            var url = "";

            if (navigationData.Parameters.Count > 0) url += "?";
            var queryString = "";
            foreach(var p in navigationData.Parameters)
            {
                if (!string.IsNullOrEmpty(queryString)) queryString += "&";
                queryString += p.Key + "=" + p.Value;
            }

            return url + queryString;
        }

    }
}
